#include "sdbusServer.hpp"

sdbusServer::~sdbusServer()
{
  if(workThread.joinable())
  {
    conn->leaveEventLoop();
    workThread.join();
  }
}

void sdbusServer::Boot()
{
  conn=sdbus::createSessionBusConnection("org.HBTY.ServerUI");
  object=sdbus::createObject(*conn,"/org/HBTY/ServerUI");

  object->registerMethod("SetBufferID")
    .onInterface(InitInterfaceName)
    .implementedAs([this](std::vector<std::string> idList){
      BufferID=std::make_optional<>(idList);
      CheckInitFinish();
    });
  object->registerMethod("SetBufferSize")
    .onInterface(InitInterfaceName)
    .implementedAs([this](long size){
      BufferSize=std::make_optional<>(size);
      CheckInitFinish();
    });
  object->registerMethod("SetCameraID")
    .onInterface(InitInterfaceName)
    .implementedAs([this](std::vector<std::string> list){
      CameraID=std::make_optional<>(list);
      CheckInitFinish();
    });
  object->registerMethod("SetMobileConnectStatus")
    .onInterface(MainInterfaceName)
    .implementedAs(SetMobileConnectStatus);
  object->registerMethod("SetRecordStatus")
    .onInterface(MainInterfaceName)
    .implementedAs(SetRecordStatus);
  object->finishRegistration();
  workThread=std::thread([this](){
    conn->enterEventLoop();
  });
}


std::vector<std::string> sdbusServer::GetBufferID()
{
  return *BufferID;
}

long sdbusServer::GetBufferSize()
{
  return *BufferSize;
}

std::vector<std::string> sdbusServer::GetCameraID()
{
  return *CameraID;
}

void sdbusServer::CheckInitFinish()
{
  if(BufferID==std::nullopt
  || BufferSize==std::nullopt
  || CameraID==std::nullopt)
    return;
  InitMut.unlock();
}
